package kyuu.acshmily.net
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import kyuu.acshmily.events.LoaderEvent;
	import kyuu.acshmily.video.VideoInfo;

	[Event(name="loadComplete", type="kyuu.acshmily.events.LoaderEvent")]

	/**
	 * 视频信息加载器<br>
	 * 加载器返回的类型始终是 Array&lt;VideoInfo&gt;
	 */
	public class PartInfoLoader extends EventDispatcher
	{
		private static const SINA_URL:String = "http://v.iask.com/v_play.php?vid=";
		private var loader:URLLoader = null;
		
		private var partName:String = "noname";

		public function PartInfoLoader(){}

		public function loadInfo(partXML:XML):void{
			if(partXML.@type == "sina"){
				partName = partXML.@name;

				try{
					// 若不存在loader实例，则实例化
					if(loader == null){
						loader = new URLLoader();
						loader.addEventListener(Event.COMPLETE, completeHandler);
						loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
					}
					// 获取sina的视频信息文件
					var sinaReq:URLRequest = new URLRequest(SINA_URL + partXML.vid);
					loader.load(sinaReq);
				}
				catch(err:Error){
					trace(err.message);
				}
			}
			else{
				var vis:Array = new Array(1);
				vis[0] = new VideoInfo(partXML.@name, partXML.url, partXML.length);
				// 调度完成事件
				var le:LoaderEvent = new LoaderEvent(LoaderEvent.LOAD_COMPLETE, false, false, vis);
				dispatchEvent(le);
				return;
			}
		}

		public function close():void{
			if(loader == null) return;

			// 释放资源
			loader.removeEventListener(Event.COMPLETE, completeHandler);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.close();
			loader = null;
		}

		/**
		 * 完成的事件处理函数
		 */
		private function completeHandler(e:Event):void{
			if(e.type != Event.COMPLETE) return;

			var le:LoaderEvent = null;
			var vis:Array = new Array();

			// 获取加载结果
			var sinaXML:XML = new XML(loader.data);

			if(sinaXML == null || sinaXML.result == "error"){
				// 不能直接返回，要调度一个事件，否则无法解析后面的视频
				le = new LoaderEvent(LoaderEvent.LOAD_COMPLETE, false, false, vis);
				dispatchEvent(le);
				return;
			}

			// 获取视频列表
			var durls:XMLList = sinaXML.durl;
			for(var i:int=0; i<durls.length(); i++){
				var durl:XML = durls[i] as XML;
				var name:String = durls.length()==1 ? partName : partName + "_" + (i+1).toString();
				vis.push(new VideoInfo(name, durl.url, durl.length));
			}
			// 调度完成事件
			le = new LoaderEvent(LoaderEvent.LOAD_COMPLETE, false, false, vis);
			dispatchEvent(le);
		}

		/**
		 * 出错的事件处理函数
		 */
		private function errorHandler(e:IOErrorEvent):void{
		}
	}
}